// const Cookiestr = require("./cookie")

// class App {
//     constructor() {
//         this.Cookiestr = new Cookiestr()
//         this.http = require('http')
//         this.querystring = require('querystring');
//         this.htmlurl = require('url');
//         this.funArr = []
//         this.server = null
//         this.cookies = []
//         this.header = []
//     }
//     updatacookie(url, cookie) {
//         let c = this.cookies.find((value) => {
//             return value.url == url
//         })
//         if (c == undefined) {
//             this.cookies.push({
//                 url,
//                 value: cookie
//             })
//         } else {
//             c.value = cookie
//         }
//     }
//     setcookie(url, key, cookie, expires) {
//         let cookiestr = typeof cookie == "string" ? cookie : JSON.stringify(cookie)
//         let value = this.Cookiestr.setCookieStr(key, cookiestr, expires)
//         this.updatacookie(url, value)
//     }
//     getcookie(cookiestr, key) {
//         return this.Cookiestr.getCookie(cookiestr, key)
//     }
//     run(prot) {
//         let _this = this
//         this.server = this.http.createServer(function (req, resp) {
//             resp.setHeader('Access-Control-Allow-Origin', '*')
//             resp.setHeader('Content-Type', 'text/html; charset=utf-8')
//             for (let i = 0; i < _this.cookies.length; i++) {
//                 console.log(req.url, ">>>>>", _this.cookies[i].url);
//                 if (req.url == _this.cookies[i].url) {
//                     console.log(_this.cookies[i].value);
//                     console.log("list>>>", _this.cookies);
//                     resp.writeHead(200, {
//                         //'text/html;charset=utf-8',application/json  }
//                         // 'Content-Type': 'text/plain; charset=utf-8',
//                         'Set-Cookie': [`${_this.cookies[i].value}`],
//                     })
//                 }
//             }

//             let url = req.url
//             console.log(url);
//             for (let i = 0; i < _this.funArr.length; i++) {
//                 let f = _this.funArr[i]
//                 f(req, resp)
//             }

//         })
//         this.server.listen(prot, () => console.log(`服务器启动成功，监听${prot}端口`))
//     }
//     post(url, a) {
//         let _this = this
//         let fun = function (req, resp) {
//             if (url == _this.htmlurl.parse(req.url, true).pathname)
//                 if (req.method == "POST") {
//                     
//                 }
//         }
//         this.funArr.push(fun)
//     }
//     get(url, a) {
//         let _this = this
//         let fun = function (req, resp) {
//             if (url == _this.htmlurl.parse(req.url, true).pathname)
//                 if (req.method == "GET") {
//                     a(_this.htmlurl.parse(req.url, true).query, req, resp)
//                 }
//         }
//         this.funArr.push(fun)
//     }
// }

// 

/*
function post(url,a){
    let fun=function (){
        if(url==req.url){
            let post=""
            req.on("data",function(chuan){
               post+=chuan
           })
           req.on("end",function(){
               post=querystring.parse(post);
               a(post) 
           })
        }
    }
    funArr.push(fun)
}

*/
const http = require('http')
const querystring = require('querystring');
const url = require('url');
const Cookie = require("./cookie")
const readmkdir = require("./file")


http.METHODSA = ["GET", "POST", "DELETE", "PUT"]
console.log(http.METHODSA)

function createApplication() {
    let mycookie = new Cookie()
    let app = {}
    app.routes = []
    app.map = new Map()
    let addapp = function () {

    }

    app.publicFile = function (pathname,path="") {
        map = readmkdir(pathname,path)
        app.use(/\..*/, (req, resp,next) => {
            console.log("资源请求", req.url);
            let url  = req.url.replace("/","")
             url = url.split("?")[0]
            let file = map.get(url)
            if(file){
               resp.end(map.get(url))   
            }else{
                console.log("资源请求", req.url,"未找到映射");
                next()
            }
        })
    }
    app.updataPath = function (oldPath,newPath){
        let file =map.get(oldPath)
        console.log(file);
        map.delete(oldPath)
        map.set(newPath,file)
    }
    function urltoReg(path) {
        path = '^' + path + "$"
        // path = path.replace("*", ".*")
        path = path.replace(/\*/g, ".*")
        let reg = new RegExp(path)
        return reg
    }


    function getcookie(key) {
        let cookiestr = this.headers.cookie
        return mycookie.getCookie(cookiestr, key)
    }

    function setcookie(key, cookie) {
        let value = mycookie.setCookieStr(key, cookie)
        this.setHeader('Set-Cookie', value)
    }

    http.METHODSA.forEach((method) => {
        method = method.toLocaleLowerCase()
        app[method] = function (path, handler) {
            if (typeof path == "string")
                path = urltoReg(path)
            let layer = {
                method,
                path,
                handler
            }
            app.routes.push(layer)
        }
    })
    app.use = function (path, handler) {
        if (typeof path === "function") {
            handler = path
            path = "/*"
        }
        if (typeof path == "string")
            path = urltoReg(path)
        layer = {
            method: "middle",
            path,
            handler
        }
        app.routes.push(layer)
    }
    app.all = function (path, handler) {
        if (typeof path === "function") {
            handler = path
            path = "/*"
        }
        if (typeof path == "string")
            path = urltoReg(path)
        layer = {
            method: "all",
            path,
            handler
        }
        app.routes.push(layer)
    }
    app.listen = function (prot, f) {
        let server = http.createServer(function (req, resp) {
            let index = 0
            let m = req.method.toLocaleLowerCase(); //请求方式
            let { //请求路径
                pathname
            } = url.parse(req.url, true);
            console.log("ip:",req.socket.remoteAddress);
            new Promise((ro, err) => { //同步函数，先获取数据先处理回调函数
                req.getcookie ? [] : req.getcookie = getcookie
                resp.setcookie ? [] : resp.setcookie = setcookie
                if (m == "post") {
                    let data = ""
                    req.on("data", function (chuan) {
                        data += chuan
                    })
                    req.on("end", function () {
                        data = querystring.parse(data);
                        req.body = data //获取post数据，传递给body
                        ro()
                    })
                } else if (m == "get") {
                    req.body = url.parse(req.url, true).query //获取get数据，传递给body
                    ro()
                }
            }).then(data => {
                next()
            })
            //递归函数遍历路由
            function next() {
                if (index === app.routes.length) { //遍历所有路由，没有返回404
                    resp.end("404")
                    return
                }
                let {
                    method,
                    path,
                    handler
                } = app.routes[index++]
                if (method === "middle") { //判断是否是中间件
                    if (typeof path === "string") //判断path是否是正则对象
                        path = urltoReg(path)
                    if (path.test(pathname)) {
                        console.log("执行", index);
                        handler(req, resp, next)
                    } else {
                        next()
                    }
                } else {
                    if (typeof path === "string")
                        path = urltoReg(path)
                    if ((m === method || method == "all") && (path.test(pathname) || path.test("*"))) {
                        console.log("执行", index);
                        handler(req, resp)
                    } else {
                        next()
                    }
                }
            }

        })
        server.listen(prot, f = () => console.log(`服务器启动成功，监听${prot}端口.文件在：`, __dirname))
    }
    return app
}

module.exports = createApplication;
console.debug()
// let app=createApplication()
// app.use((req,resp,next)=>{ 
//     resp.setHeader('Access-Control-Allow-Origin', '*')
//     resp.setHeader('Content-Type', 'text/html; charset=utf-8')
//     next()
// })

// app.get("/login",(req,resp)=>{
//     resp.write("登录")
// })
// app.listen(8090)